package com.haiheng.module_main.fragment

import android.annotation.SuppressLint
import android.app.ScansManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.haiheng.common.constant.RourePage
import com.haiheng.common.fragment.RouterFragment
import com.haiheng.library_base.dialog.LoadingDialog
import com.haiheng.library_base.model.ApplicationViewModel
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.msg.MsgCode
import com.haiheng.library_base.msg.MsgEvent
import com.haiheng.library_base.toast.ToastUtils
import com.haiheng.library_base.utils.FastClickUtil
import com.haiheng.module_main.R
import com.haiheng.module_main.adapter.BookListAdapter
import com.haiheng.module_main.databinding.FragmentFindAndLocateBinding
import com.haiheng.module_main.dialog.BookDetailDialog
import com.haiheng.module_main.mode.BookInfoViewModel
import kotlinx.coroutines.launch

/**
 *
 * @Des: 查找定位
 * @Author: hwz
 * @Date:2023/6/17 0017
 * @Version: 1.0
 */
class FindAndLocateFragment : RouterFragment() {
    private lateinit var binding:FragmentFindAndLocateBinding
    private val viewMode : BookInfoViewModel by viewModels()
    private val bookListAdapter = BookListAdapter()

    private var mScansManager: ScansManager? = null
    private lateinit var loadingDialog : LoadingDialog
    private var conditionName:String = "barCode"

    private val observer = Observer<MsgEvent> { msgEvent ->
        onMessageChange(msgEvent)
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentFindAndLocateBinding.inflate(inflater, container, false)
        return binding.root
    }
    override fun initView() {
        loadingDialog = LoadingDialog(requireContext(), R.style.AvLoadingDialogStyle)
        binding.includeTile.tvTitle.setText(getText(R.string.text_find_and_locate))
        binding.includeTile.ivBack.setOnClickListener {
            activity.navigateUp()
        }
        binding.includeTile.cbRignt.isChecked = false
        binding.includeTile.cbRignt.setOnClickListener {
            binding.includeTile.cbRignt.isChecked = true
        }

        binding?.rvBookList?.layoutManager = LinearLayoutManager(activity)
        bookListAdapter.setPageType(RourePage.FIND_AND_LOCATE.name)
        bookListAdapter.setHidenCheck(true)
        binding?.rvBookList?.adapter = bookListAdapter

        bookListAdapter.setOnItemClickListener(object : com.haiheng.library_base.adapter.BaseAdapter.OnItemClickListener{
            override fun onItemClick(
                holder: com.haiheng.library_base.adapter.BaseAdapter.ViewBindHolder,
                position: Int
            ) {
                BookDetailDialog.newInstance()
                    .setBookDetail(bookListAdapter.getItem(position))
                    .show(childFragmentManager)
            }
        })

        val adapter = ArrayAdapter.createFromResource(
            activity,
            R.array.search_array,  // 字符串数组资源，用于显示下拉列表中的选项
            android.R.layout.simple_spinner_item  // Spinner 的布局样式
        )
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spSearch.adapter = adapter
        binding.spSearch.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
                val selectedText = parent.getItemAtPosition(position).toString()
                conditionName = when(selectedText){
                    "书名"->"bookTitle"
                    "作者"->"author"
                    "条码号"->"barCode"
                    "索书号"->"callNumber"
                    "ISBN"->"isbn"
                    else -> {"barCode"}
                }

            }

            override fun onNothingSelected(parent: AdapterView<*>) {
                // 当没有选中项时的回调方法
            }
        }
        binding.btnSearch.setOnClickListener {
            search()
        }

        binding.etSearch.setOnEditorActionListener {  v, keyCode, event ->
            if(keyCode == EditorInfo.IME_ACTION_SEARCH) {
                search()
                false
            }
            false
        }
        binding.tvClear.setOnClickListener {
            viewMode._bookListData.postValue(listOf())
            binding.includeTile.cbRignt.isChecked = false
            binding.etSearch.setText("")
        }
    }

    fun search(){
        var fileValue = binding.etSearch.text
        if (fileValue.isNotBlank()){
            viewMode.searchBookLisbByCondition(conditionName,fileValue.toString(),1)
        }else{
            ToastUtils.showShort("查找内容不能为空")
        }
    }

    override fun onResume() {
        super.onResume()
        observEven()
    }

    override fun onPause() {
        super.onPause()
        clearMsg()
        mScansManager?.stopScan()
    }

    override fun initViewModel(): BaseViewModel? {
        viewMode.bookListData.observe(viewLifecycleOwner){
            binding.tvBookNum.setText("数量：${it.size}")
            bookListAdapter.setNewData(it)
        }
        viewMode.showMsg.observe(viewLifecycleOwner){
            ToastUtils.showShort(it)
            loadingDialog.hide()
        }


        viewMode._bookInfoByBarcode.observe(viewLifecycleOwner){ bookInfo->
            lifecycleScope.launch {
                val dataList = bookListAdapter.getData()
                dataList.forEach {
                    if (it.barCode.toString().equals(bookInfo.barCode)){
                        it.isSelect = true
                        return@forEach
                    }
                }
                dataList.sortByDescending { it.isSelect }
                bookListAdapter.notifyDataSetChanged()
            }
        }
        return viewMode
    }

    private fun onMessageChange(msgEvent: MsgEvent?) {
        when (msgEvent?.code){
            MsgCode.MSG_SCANS_BARCODE->{
                if (FastClickUtil.isFaskMsg(msgEvent.msg,200)) return //两次相同消息太快这不处理
                if (binding.includeTile.cbRignt.isChecked){
                    viewMode.searchBookInfoByBarCode(msgEvent.msg)
                }else{
                    binding.etSearch.setText(msgEvent.msg)
                    search()
                }
            }
        }
    }

    private fun observEven() {
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
            ApplicationViewModel.get().even.observe(this,observer)
        }
    }
    fun clearMsg(){
        if (ApplicationViewModel.get().even != null) {
            if (ApplicationViewModel.get().even.hasObservers()) {
                ApplicationViewModel.get().even.removeObserver(observer)
            }
        }
    }

    @SuppressLint("WrongConstant")
    override fun initLoad() {
        var manager   = activity.getSystemService("scans")
        if (manager != null){
            mScansManager = manager as ScansManager
            mScansManager?.persistMode =true
        }

    }

}